var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
var session = require('express-session');
var lRouter = require('./routes/l'); //登录
var rRouter = require('./routes/r'); //注册
var pwdRouter = require('./routes/pwd'); //更改密码
var mdetailRouter = require('./routes/mdetail'); //加载建材详情
var cartRouter = require('./routes/cart'); //检查购物车内是否已有该商品
var insertRouter = require('./routes/insert'); //增加用户、添加商品至购物车、修改密码
var usersRouter = require('./routes/users'); //个人资料
var wkpRouter = require('./routes/workplace'); //工地
var bdetailRouter = require('./routes/buyDetail'); //订单详情
var plRouter = require('./routes/pl'); //磅单
var billRouter = require('./routes/bill'); //磅单
var app = express();

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');

app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({
  extended: false
}));
app.use(cookieParser());
app.use(session({
  secret: 'keyboard cat',
  resave: true,
  saveUninitialized: true
}))
// app.use(session({
//   secret: 'sessiontest',//与cookieParser中的一致
//   resave: true,
//   saveUninitialized:true
// }));
app.use(express.static(path.join(__dirname, 'public')));


app.use('/users', usersRouter);
app.use('/l', lRouter);
app.use('/r', rRouter);
app.use('/pwd', pwdRouter);
app.use('/mdetail', mdetailRouter);
app.use('/cart', cartRouter);
app.use('/insert', insertRouter);
app.use('/workplace', wkpRouter);
app.use('/buyDetail', bdetailRouter);
app.use('/pl', plRouter);
app.use('/bill', billRouter);
// catch 404 and forward to error handler
app.use(function (req, res, next) {
  next(createError(404));
});

// error handler
app.use(function (err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render('error');
});

module.exports = app;